/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kizitonwose.calendarview.utils;

import ohos.agp.components.AttrSet;

/**
 * AttrUtils
 *
 * @since 2021-02-26
 */
public class AttrUtils {
    /**
     * getAttrValue
     *
     * @param attrSet AttrSet
     * @param attrKey String
     * @param t Object
     * @param <T> 泛型T
     * @return Object
     */
    public static <T> T getAttrValue(AttrSet attrSet, String attrKey, Object t) {
        Object m = t;
        if (attrSet == null) {
            return (T) m;
        }
        if (attrSet.getAttr(attrKey).isPresent()) {
            if (t instanceof String) {
                m = attrSet.getAttr(attrKey).get().getStringValue();
            } else if (t instanceof Integer) {
                m = attrSet.getAttr(attrKey).get().getIntegerValue();
            }
        }
        return (T) m;
    }

    /**
     * 获取资源文件id 格式 $layout:布局名称
     *
     * @param attrSet AttrSet
     * @param resourceKey String
     * @return id
     */
    public static int getResourceId(AttrSet attrSet, String resourceKey) {
        String errorStr = "请确认布局中是否添加正确的自定义资源文件，格式@layout:布局名称";
        int resourceId = 0;
        if (attrSet.getAttr(resourceKey).isPresent()) {
            String value = attrSet.getAttr(resourceKey).get().getStringValue();
            if (value.contains(":")) {
                try {
                    resourceId = Integer.parseInt(value.substring(value.indexOf(":") + 1));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    System.out.println(errorStr);
                }
            } else {
                try {
                    throw new Exception(errorStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return resourceId;
    }
}
